package com.haisen.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.haisen.core.utils.InsertBatch;
import com.haisen.core.utils.MyMapper;
import com.haisen.core.utils.PageResultSet;
import com.haisen.dataobject.entity.BussItem;
import com.haisen.dataobject.entity.BussItemT;
import com.haisen.dataobject.entity.User;
import com.haisen.dataobject.mapper.base.BussItemMapper;
import com.haisen.dataobject.query.BussItemQuery;
import com.haisen.exception.BizException;
import com.haisen.poi.basic_poi.BigExcelUtil;
import com.haisen.service.BussItemService;
import com.haisen.service.OrganizationService;
import com.haisen.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BussItemServiceImpl implements BussItemService {

    @Autowired
    private BussItemMapper bussItemMapper;
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    private InsertBatch<BussItem> batchAdd = null;
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;

    @Override
    public void create(BussItem bussItem) {
        bussItemMapper.insertSelective(bussItem);
    }

    @Override
    public void update(BussItem bussItem) {
       bussItemMapper.updateByPrimaryKeySelective(bussItem);
    }

    @Override
    public void delete(Long[] ids) {
        Weekend<BussItem> example = Weekend.of(BussItem.class);
        WeekendCriteria<BussItem,Object> criteria = example.weekendCriteria();
        criteria.andIn(BussItem::getId, Arrays.asList(ids));
        bussItemMapper.deleteByExample(example);
    }

    @Override
    public void createbatch(List<BussItem> bussItemList) {
        SqlSession sqlSession= sqlSessionFactory.openSession(ExecutorType.BATCH);
        MyMapper<BussItem> myMapper = (MyMapper<BussItem>) sqlSession.getMapper(BussItemMapper.class);
        batchAdd = new InsertBatch<>();
        batchAdd.insertBatch(sqlSession,myMapper,bussItemList);
    }

    /**
     * 根据用户所在部门岗位，查看权限的不同
     * @param bussItemQuery
     * @return
     */
    @Override
    public PageResultSet<BussItem> findByPage(BussItemQuery bussItemQuery) {
        //分页参数设置
        if (!StringUtils.isEmpty(bussItemQuery.getOrderBy())){
            PageHelper.orderBy(bussItemQuery.getOrderBy());
        }
        PageHelper.offsetPage(bussItemQuery.getOffset(),bussItemQuery.getLimit());

        Weekend<BussItem> example = Weekend.of(BussItem.class);
        WeekendCriteria<BussItem,Object> criteria = example.weekendCriteria();
        //todo：日期大于，注意为字符串比较大小，是否要转换为日期型,小于和等于
       // log.info("{}",bussItemQuery.getSearchDate());
        if (!StringUtils.isEmpty(bussItemQuery.getBeginDate())){
            criteria.andGreaterThanOrEqualTo(BussItem::getCdate,bussItemQuery.getBeginDate());
        }
         //小于截至日期
        if (!StringUtils.isEmpty(bussItemQuery.getEndDate())){
            criteria.andLessThanOrEqualTo(BussItem::getCdate,bussItemQuery.getEndDate());
        }

        if (!StringUtils.isEmpty(bussItemQuery.getPhone())){
            criteria.andEqualTo(BussItem::getPhone,bussItemQuery.getPhone());
        }
        if (!StringUtils.isEmpty(bussItemQuery.getOrganizationNo())){
            criteria.andEqualTo(BussItem::getOrganizationNo,bussItemQuery.getOrganizationNo());
        }
        if (!StringUtils.isEmpty(bussItemQuery.getOrganizationNo())){
            criteria.andLike(BussItem::getOrganizationNo,bussItemQuery.getOrganizationNo());
        }
        if (!StringUtils.isEmpty(bussItemQuery.getEmployer())){
            criteria.andLike(BussItem::getEmployer,bussItemQuery.getEmployer());
        }

        //数据权限设置 todo:管理员帐户写死了
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        User user = userService.findByUsername(username);
        if (user == null) throw new BizException("找不到用户:" + username);

        List<Long> roleIds = new ArrayList<>();
        roleIds.add(Long.valueOf(1));
        roleIds.add(Long.valueOf(2));
        //todo：管理员权限有问题，用手机号码登录测试下
        List<String> adminRole = user.getRoleIdList().stream().filter(o ->{
            if(roleIds.contains(o)) return true;
            else return false;
        }).map( o-> {
            return o.toString();
        }).collect(Collectors.toList());

        if(adminRole.size() >0 || user.getRoleIdList().contains("1")) {
            return dataPage(example);
        }

         //按部门筛选
        List<String> leadInDeptsList = user.getLeadInDeptsList();
        if (leadInDeptsList.size() > 0) {
            log.info("{},拥有数据权限", user.getNickName());
            Long[] ids = new Long[user.getLeadInDeptsList().size()];
            for (int i = 0; i < leadInDeptsList.size(); i++) {
                ids[i] = Long.valueOf(leadInDeptsList.get(i));
            }
            //根据orgid查找name
            final List<String> orgNoList = organizationService.findByIds(ids);
            if (orgNoList.size() >0 ) {
                criteria.andIn(BussItem::getOrganizationNo, orgNoList);
                return dataPage(example);
            }
        }
         //员工
          if (!StringUtils.isEmpty(user.getNickName())){
            criteria.andEqualTo(BussItem::getEmployer,user.getNickName());
          }

        return dataPage(example);
    }

    private PageResultSet<BussItem> dataPage(Weekend example){
        //排序
        example.setOrderByClause("id desc");
        List<BussItem> bussItemList = bussItemMapper.selectByExample(example);
        long total = bussItemMapper.selectCountByExample(example);
        PageResultSet<BussItem> resultSet = new PageResultSet<>();
        resultSet.setRows(bussItemList);
        resultSet.setTotal(total);
        return resultSet;
    }


    @Override
    public void importExcel2DataBase(String pathFile) {
        BigExcelUtil bigExcelUtil = BigExcelUtil.getInstance();
        List<Object> objs =  bigExcelUtil.importExcel2Obj(pathFile,BussItem.class);
        log.info("读取excel：{}", JSON.toJSONString(objs));
        List<BussItem> bussItemList = objs.stream()
                .filter(o -> {
                    if (!StringUtils.isEmpty(((BussItem)o).getBizType())) return true;
                    else return false;
                })
                .map( o ->{
            return (BussItem)o;
        }).collect(Collectors.toList());
        createbatch(bussItemList);

    }

    /**
     * 根据id修改状体
     * @param ids
     * @param stauts
     */
    @Override
    public void verifyDate( Integer stauts,Long[] ids) {
        bussItemMapper.updateStatus(stauts,ids);
    }
}
